package com.funmi.lizip.controller;

import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.write.style.column.LongestMatchColumnWidthStyleStrategy;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.plugins.pagination.PageDTO;
import com.funmi.lizip.common.base.R;
import com.funmi.lizip.common.base.ResultCode;
import com.funmi.lizip.common.exception.ApplicationException;
import com.funmi.lizip.entity.Device;
import com.funmi.lizip.entity.TaskDelivery;
import com.funmi.lizip.entity.dto.task.TaskQueryRequest;
import com.funmi.lizip.entity.dto.taskDelivery.TaskDeliveryAddRequest;
import com.funmi.lizip.entity.dto.taskDelivery.TaskDeliveryQueryRequest;
import com.funmi.lizip.entity.dto.taskDelivery.TaskDeliveryUpdateRequest;
import com.funmi.lizip.entity.vo.TaskDeliveryVo;
import com.funmi.lizip.entity.vo.TaskVo;
import com.funmi.lizip.service.TaskDeliveryService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.URLEncoder;
import java.time.LocalDateTime;
import java.util.List;
import java.util.stream.Collectors;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author itheima
 */
@Slf4j
@RestController
@Api(tags = "数据采集和核查")
@RequestMapping("taskDelivery")
public class TaskDeliveryController {

    @Autowired
    private TaskDeliveryService  taskDeliveryService;

    @ApiOperation(value = "任务下发的新增")
    @PostMapping("")
    public R addTaskDelivery(@RequestBody TaskDeliveryAddRequest request){
        if(request==null){
            throw new ApplicationException(ResultCode.NOT_FOUND);
        }

        request.setCreateAt(LocalDateTime.now());
        request.setIsDelete(false);

        TaskDelivery taskDelivery = new TaskDelivery();
        BeanUtils.copyProperties(request,taskDelivery);
        boolean save = taskDeliveryService.save(taskDelivery);

        if (save) {
            return R.success().message("新增成功");
        } else {
            throw new ApplicationException("新增失败");
        }
    }

    @ApiOperation(value = "任务下发的修改")
    @PutMapping("/{id}")
    public R updateTaskDelivery(@RequestBody(required = false) TaskDeliveryUpdateRequest request){
        if(request==null||request.getId()==null){
            throw new ApplicationException(ResultCode.NOT_FOUND);
        }
        TaskDelivery taskDelivery = new TaskDelivery();
        BeanUtils.copyProperties(request,taskDelivery);

        boolean update = taskDeliveryService.updateById(taskDelivery);
        if (update) {
            return R.success().message("修改成功");
        } else {
            throw new ApplicationException("修改失败");
        }
    }

    @ApiOperation(value = "任务下发的删除")
    @DeleteMapping("/{id}")
    public R deleteTaskDelivery(@PathVariable Integer id){
        if (id <= 0) {
            throw new ApplicationException(ResultCode.FILE_DELETE_ERROR);
        }
        boolean result = taskDeliveryService.removeById(id);
        if (result) {
            return R.success().message("删除成功");
        } else {
            return R.fail().message("删除失败");
        }
    }

    @ApiOperation("根据任务下发输入进行检索")
    @GetMapping("")
    public R listPage(TaskDeliveryQueryRequest request){
        long current = 1;
        long size = 5;
        TaskDelivery taskDeliveryQuery = new TaskDelivery();
        if(request!=null){
            BeanUtils.copyProperties(request,taskDeliveryQuery);
            current =request.getPage();
            size =request.getPageSize();
        }

        QueryWrapper<TaskDelivery> qw =new QueryWrapper<>(taskDeliveryQuery);
        qw.select().orderByDesc("create_at");

        Page<TaskDelivery> deliveryPage = taskDeliveryService.page(new Page<>(current, size), qw);

        PageDTO<TaskDeliveryVo> taskDeliveryVoPage = new PageDTO<>(deliveryPage.getCurrent(), deliveryPage.getSize(), deliveryPage.getTotal());

        List<TaskDeliveryVo> taskDeliveryVoList = deliveryPage.getRecords().stream().map(taskDelivery -> {
            TaskDeliveryVo taskDeliveryVo = new TaskDeliveryVo();
            BeanUtils.copyProperties(taskDelivery, taskDeliveryVo);
            return taskDeliveryVo;
        }).collect(Collectors.toList());
        taskDeliveryVoPage.setRecords(taskDeliveryVoList);
        return R.success().data(taskDeliveryVoPage);
    }

    @ApiOperation("根据任务下发表的id查询列表")
    @GetMapping("/{id}")
    public R listById(TaskDeliveryQueryRequest request){
        if(request==null ){
            throw new ApplicationException(ResultCode.NOT_FOUND);
        }
        TaskDelivery taskDelivery= taskDeliveryService.listById(request);
        if(taskDelivery==null){
          return R.fail().message("id不存在");
        }
        return  R.success().data(taskDelivery);
    }


    @Transactional(rollbackFor = Exception.class)
    @ApiOperation("任务下发导出到excel")
    @GetMapping("/exportListExcel")
    public void exportListExcel(@RequestParam(required = false) Integer  taskId, HttpServletResponse response) throws IOException {

        TaskDeliveryQueryRequest taskDeliveryQueryRequest = new TaskDeliveryQueryRequest();
        taskDeliveryQueryRequest.setTaskId(taskId);

        List<TaskDelivery> list = taskDeliveryService.getAll(taskDeliveryQueryRequest);

        //List<TaskDelivery> list = taskDeliveryService.getAll();
        for (TaskDelivery taskDelivery : list) {
            String status = taskDelivery.getStatus();
            if("1".equals(status)){
                taskDelivery.setStatus("已下发");
            }else  if ("2".equals(status)){
                taskDelivery.setStatus("已接受");
            }else  if ("3".equals(status)){
                taskDelivery.setStatus("进行中");
            }else  if ("4".equals(status)){
                taskDelivery.setStatus("已完成");
            }else {
                taskDelivery.setStatus("");
            }

        }


        String fileName = URLEncoder.encode("任务下发清单.xlsx", "UTF-8");
        EasyExcel.write(fileName, TaskDelivery.class)
                .registerWriteHandler(new LongestMatchColumnWidthStyleStrategy()).sheet("任务下发清单清单")
                .doWrite(list);
        File file = new File(fileName);
        // 通知浏览器进行文件下载
        response.setContentType("application/x-download");
        response.setCharacterEncoding("UTF-8");
        response.addHeader("Content-Disposition", "attachment;filename=" + fileName);
        InputStream stream = new FileInputStream(file);
        ServletOutputStream out = response.getOutputStream();
        byte buff[] = new byte[1024];
        int length = 0;
        while ((length = stream.read(buff)) > 0) {
            out.write(buff, 0, length);
        }

        stream.close();
        out.close();
        out.flush();

    }
}
